package com.etop.learnapp.activity;

import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.LinearLayout;

import com.etop.learnapp.R;

/**
 * Created by John on 2015/12/14.
 */
public class TestDetailActivity extends AppCompatActivity implements SurfaceHolder.Callback{
    private MediaPlayer mediaPlayer;
    private SurfaceView surfaceView;
    private SurfaceHolder surfaceHolder;
    private int resID;
    private LinearLayout ll;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_testd);
        ll= (LinearLayout) findViewById(R.id.linearLayout1);
        ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initView();
            }
        });

    }
    private void initView()
    {

        surfaceView = new SurfaceView(this);
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                720);
        lp.setMargins(5, 10, 5, 10);
        surfaceView.setLayoutParams(lp);
        surfaceHolder = surfaceView.getHolder();
        surfaceHolder.addCallback(this);
        ll.addView(surfaceView);
        int keySelect =  getIntent().getIntExtra("keySelect", -1);
        String fileName="sp5_"+keySelect;
        resID=getResources().getIdentifier(fileName,"raw",getPackageName());
    }
    class PlayMovie extends Thread {   //播放视频的线程

        int post = 0;

        public PlayMovie(int post) {
            this.post = post;

        }

        @Override
        public void run() {
            Message message = Message.obtain();
            try {
                mediaPlayer = MediaPlayer.create(TestDetailActivity.this, resID);
                mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                mediaPlayer.setDisplay(surfaceHolder);
                mediaPlayer.start();
            } catch (Exception e) {
                message.what = 2;
                Log.e("hck", e.toString());
            }
            super.run();
        }
    }
    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        new PlayMovie(0).start();
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
        }
        System.gc();
    }
}
